package com.helloapp.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.helloapp.dao.UserDao;
import com.helloapp.dao.impl.UserDaoImpl;
import com.helloapp.entity.LoginVO;
import com.helloapp.entity.User;

@WebServlet("/loginapi")
public class LoginApiServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//request.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(username);
		System.out.println(password);

		PrintWriter pw = response.getWriter();
		String s = "{ \"msg\":\"OK\",\"type\":1}";

		UserDao userDao = new UserDaoImpl();
		User u = userDao.getByUsernameAndPassword(username, password);
		// 判断用户名与密码是否正确
		if (u!=null && u.getUsername() != null) {
			request.getSession().setAttribute("username", username);

			// 清除Cookie
			Cookie[] cookies = request.getCookies();
			if (cookies != null && cookies.length > 0) {
				for (Cookie c : cookies) {
					if (c.getName().equals("remember")) {
						c.setMaxAge(0);
						response.addCookie(c);
					}
				}
			}

			request.getSession().removeAttribute("error");
			//response.sendRedirect("main.jsp");
			LoginVO loginVO = new LoginVO("main.jsp",1);
			Gson g = new Gson();
			s = g.toJson(loginVO);
			//s = "{ \"url\":\"main.jsp\",\"type\":1}";
			
		} else {
			request.getSession().setAttribute("error", "用户名或密码错误");
			//response.sendRedirect("login.jsp");
			LoginVO loginVO = new LoginVO("login2.jsp",0);
			Gson g = new Gson();
			s = g.toJson(loginVO);
			//s = "{ \"url\":\"login2.jsp\",\"type\":0}";
		}

		pw.write(s);
		pw.close();
	}
}
